﻿ 
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto.WorkingCenter;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Entity.WorkingCenter;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace SHKF.B2C.BLL
{
    public class WorkingCenterBLL : BaseBll
    {
        public WorkingCenterBLL(SqlSugarClient db) : base(db)
        {
            db.ChangeDatabase("PtE_YZY_WorkingCenter");
        }


        /// <summary>
        /// 通过分仓SN获取数据,就得保证分仓唯一
        /// </summary>
        /// <param name="WarehousSN"></param>
        /// <returns></returns>
        public ShopRelatedEntity QueryShopRelate(string WarehousSN)
        {
            ShopRelatedEntity info = this.db
                .Queryable<ShopRelatedEntity>()
                .Where(ww => ww.WarehousSN == WarehousSN)
                .First();

            return info;
        }

        /// <summary>
        /// 获取erp门店映射
        /// </summary>
        /// <param name="shopVSN">虚拟门店SN</param>
        /// <returns></returns>
        public List<ShopRelatedEntity> QueryShopRelateList(long shopVSN)
        {
            List < ShopRelatedEntity > list= this.db
                .Queryable<ShopRelatedEntity>()
                .Where(ww => ww.ShopVSN == shopVSN)
                .ToList();

            return list;
        }
         
        /// <summary>
        /// 获取Erp产品映射关系
        /// </summary>
        /// <param name="WarehousSN">分仓SN</param>
        /// <param name="ProductSN">epr产品SN</param>
        /// <returns></returns>
        //public ProductInfoRelatedEntity QueryProductInfoRelated(string WarehousSN, string Upc)
        //{
        //    ProductInfoRelatedEntity info = this.db
        //        .Queryable<ProductInfoRelatedEntity>()
        //        .Where(ww => ww.WarehousSN == WarehousSN && ww.ProductVSN == Upc)
        //        .First();

        //    return info;
        //}

        /// <summary>
        /// 获取虚拟产品SN的erp产品SN列表
        /// </summary>
        /// <param name="ProductVSN"></param>
        /// <returns></returns>
        //public List<ProductInfoRelatedEntity> QueryProductInfoRelatedList(long ProductVSN)
        //{
        //   List< ProductInfoRelatedEntity> list = this.db
        //        .Queryable<ProductInfoRelatedEntity>()
        //        .Where(ww => ww.ProductVSN == ProductVSN)
        //        .ToList();

        //    return list;
        //}

        //更新B2C平台库存
        public UpErpQtyDto UpdateProductQty(string WarehousSN, long ProductSN, int Qty)
        {
            UpErpQtyDto dto = new UpErpQtyDto();
            string Platform = PlatformEnum.YouZanYun;

            //--------------------1.获取有赞云分店SN
            ShopRelatedEntity shopRelatedEntity = this.QueryShopRelate(WarehousSN);
            if (shopRelatedEntity == null || shopRelatedEntity.ShopVSN == 0)
            {
                //this.logger.LogError($"ProductSN:{ProductSN} >> 门店:{WarehousSN}在Erp中没有映射!");
                dto.Qty = -1;
                return dto;
            }

            int ShopVSN = shopRelatedEntity.ShopVSN;            //虚拟分店SN 
            this.db.ChangeDatabase("PtE_Center");

            ShopMapEntity shopMap = this.db
              .Queryable<ShopMapEntity>()
              .Where(oo => oo.ShopSN == ShopVSN && oo.Platform == Platform)
              .First();
 
            if (shopMap == null || shopMap.app_poi_code == 0)
            {
                //this.logger.LogError($"ProductSN:{ProductSN} 门店:{ShopVSN}在B2C中没有映射!");
                dto.Qty = -1;
                return dto;
            } 
            long node_kdt_id = shopMap.app_poi_code; //有赞分店SN

            //--------------------2.获取有赞云产品SN
            //this.db.ChangeDatabase("PtE_YZY_WorkingCenter");
            //ProductInfoRelatedEntity productRelate = this.QueryProductInfoRelated(WarehousSN, ProductSN);
            //if (productRelate == null || productRelate.ProductVSN == 0)
            //{
            //    //this.logger.LogError($"ProductSN:{ProductSN} 在Erp中没有映射!");
            //    dto.Qty = -1;
            //    return dto;
            //}
            //long productVSV = productRelate.ProductVSN;

            //this.db.ChangeDatabase("PtE_Center");
            //ProductInfoMapEntity productMap = this.db
            //   .Queryable<ProductInfoMapEntity>()
            //   .Where(ww => ww.Upc == productVSV && ww.Platform == Platform)
            //   .First();
             
            //if (productMap == null || productMap.app_medicine_id == "")
            //{
            //    //this.logger.LogError($"ProductSN:{ProductSN}  虚拟产品SN:{productVSV} 没有配置有赞云平台产品SN!");
            //    dto.Qty = -1;
            //    return dto;
            //}

            //int result = CalcQty(ShopVSN, WarehousSN, productVSV, ProductSN, Qty);
            //dto.Qty = result;
            //dto.ShopVSN = ShopVSN;
            //dto.ProductVSN = productVSV;

            return dto;
        }

        /// <summary>
        /// 用于计算分仓下当前品所有库存
        /// </summary>
        /// <param name="ShopVSN"></param>
        /// <param name="ProductVSN"></param>
        /// <returns></returns>
        private int CalcQty(int ShopVSN, string warehousSN, long ProductVSN, long ProductSN, int Qty)
        {
            this.db.ChangeDatabase("PtE_YZY_WorkingCenter");
            int totalQty = 0;
            try
            {
                this.db.BeginTran();

                //更新分仓
                WareHouseDataWarehousEntity info = this.db.Queryable<WareHouseDataWarehousEntity>()
                    .Where(ww => ww.ShopVSN == ShopVSN
                    && ww.WarehousSN == warehousSN
                      && ww.ProductVSN == ProductVSN
                        && ww.ProductSN == ProductSN)
                    .First();

                if (info != null)
                {
                    info.Qty += Qty;
                    this.db.Updateable<WareHouseDataWarehousEntity>(info)
                        .ExecuteCommand();
                }
                else
                {
                    info = new WareHouseDataWarehousEntity();
                    info.ShopVSN = ShopVSN;
                    info.WarehousSN = warehousSN;
                    info.ProductVSN = ProductVSN;
                    info.ProductSN = ProductSN;
                    info.Qty = Qty;
                    this.db.Insertable<WareHouseDataWarehousEntity>(info)
                           .ExecuteCommand();
                }

                //所有分仓下的总数　 
                totalQty = db.Queryable<WareHouseDataWarehousEntity>()
                    .Where(ww => ww.ShopVSN == ShopVSN && ww.ProductVSN == ProductVSN)
                    .Sum(it => it.Qty);

                //更新总仓
                int result = 0;
                WareHouseDataAllEntity oldInfo = this.db
                    .Queryable<WareHouseDataAllEntity>()
                    .Where(ww => ww.ShopVSN == info.ShopVSN
                           && ww.ProductVSN == info.ProductVSN)
                    .First();

                if (oldInfo != null)
                {
                    oldInfo.Qty = totalQty;
                    result = this.db.Updateable<WareHouseDataAllEntity>(oldInfo)
                        .ExecuteCommand();
                }
                else
                {
                    result = this.db.Insertable<WareHouseDataAllEntity>(info)
                        .ExecuteCommand();
                }

                this.db.CommitTran();
            }
            catch (Exception ex)
            {
                this.db.RollbackTran();
                throw ex;
            }
            
            return totalQty;


        }


        /// <summary>
        /// 明细账
        /// </summary>
        /// <param name="ShopVSN"></param>
        /// <param name="ProductVSN"></param>
        /// <param name="WarehousSN"></param>
        /// <param name="ProductSN"></param>
        /// <param name="Forward"></param>
        /// <param name="Rubric"></param>
        /// <param name="Qty"></param>
        /// <param name="Summary"></param>
        /// <param name="Memo"></param>
        /// <returns></returns>
        public int SaveBalanceAmount(int ShopVSN, long ProductVSN, 
            string WarehousSN, long ProductSN, int Forward, int Rubric, int Qty, string Summary, string Memo)
        {
            decimal AddWarehousQty = 0; 
            decimal BWarehousQty = 0;   //分仓结余数量

            decimal AllWarehousQty = 0; //总库存结余数量

            this.db.ChangeDatabase(DB_YZY_WorkingCenter);

            #region 分店明细

            if (Rubric == 0)
            {
                if (Rubric == 0)
                {
                    AddWarehousQty = Qty;
                }
                else
                {
                    AddWarehousQty = Qty * -1;
                }
            }
            else
            {
                if (Rubric == 0)
                {
                    AddWarehousQty = Qty * -1;
                }
                else
                {
                    AddWarehousQty = Qty;
                }
            }

            //处理分仓库存及明细账	  
            PABalanceWarehousEntity balanceInfo = this.db.Queryable<PABalanceWarehousEntity>()
                .Where(ww => ww.ShopVSN == ShopVSN
                          && ww.ProductVSN == ProductVSN
                          && ww.WarehousSN == WarehousSN
                          && ww.ProductSN == ProductSN)
                .First();
            if (balanceInfo != null)
            {
                BWarehousQty = balanceInfo.BalanceAmount;
            }

            ProductAccountWarehous accountWarehous = new ProductAccountWarehous();
            accountWarehous.ShopVSN = ShopVSN;
            accountWarehous.ProductVSN = ProductVSN;
            accountWarehous.WarehousSN = WarehousSN;
            accountWarehous.ProductSN = ProductSN;
            accountWarehous.Rubric = Rubric; 
            accountWarehous.Summary = Summary;
            accountWarehous.Memo = Memo;
            accountWarehous.pDate = DateTime.Now;

            if (Forward == 0)
            {
                if (Rubric == 0)
                {
                    BWarehousQty += Qty;
                }
                else
                {
                    BWarehousQty -= Qty;
                }

                accountWarehous.DebitAmount = Qty;
                accountWarehous.CreditAmount = 0;
            }
            else
            {
                if (Rubric == 0)
                {
                    BWarehousQty -= Qty;
                }
                else //红字
                {
                    BWarehousQty += Qty;
                }
                accountWarehous.DebitAmount = 0;
                accountWarehous.CreditAmount = Qty;
            } 
            accountWarehous.BalanceAmount = BWarehousQty;

            //保存明细
            this.db
                   .Insertable<ProductAccountWarehous>(accountWarehous)
                   .ExecuteCommand();

            #endregion

            #region 分店结余

            //保存分店结余
            if (balanceInfo == null)
            {
                balanceInfo = new PABalanceWarehousEntity();
                balanceInfo.ShopVSN = ShopVSN;
                balanceInfo.ProductVSN = ProductVSN;
                balanceInfo.WarehousSN = WarehousSN;
                balanceInfo.ProductSN = ProductSN;
                balanceInfo.BalanceAmount = BWarehousQty;
                balanceInfo.pDate = DateTime.Now;

                this.db
                    .Insertable<PABalanceWarehousEntity>(balanceInfo)
                    .ExecuteCommand();
            }
            else
            {
                balanceInfo.BalanceAmount = BWarehousQty;
                this.db
                    .Updateable<PABalanceWarehousEntity>(balanceInfo)
                    .ExecuteCommand();
            }

            #endregion

            #region 总明细

            //-----------总明细
            PABalanceAllEntity balanceAllInfo = this.db.Queryable<PABalanceAllEntity>()
                .Where(ww => ww.ShopVSN == ShopVSN
                    && ww.ProductVSN == ProductVSN)
                .First();
            if (balanceAllInfo != null)
            {
                AllWarehousQty = balanceAllInfo.BalanceAmount;
            }

            ProductAccountAll AccountAll = new ProductAccountAll();
            AccountAll.ShopVSN = ShopVSN;
            AccountAll.ProductVSN = ProductVSN;
            AccountAll.Rubric = Rubric;
            AccountAll.pDate = DateTime.Now;
            AccountAll.Summary = Summary;
            AccountAll.Memo = Memo;

            if (Forward == 0)
            {
                if (Rubric == 0)
                {
                    AllWarehousQty += Qty; 
                }
                else
                {
                    AllWarehousQty -= Qty;
                }

                AccountAll.DebitAmount = Qty;
                AccountAll.CreditAmount = 0;
            }
            else
            {
                if (Rubric == 0)
                {
                    AllWarehousQty -= Qty;
                }
                else
                {
                    AllWarehousQty += Qty;
                }

                AccountAll.DebitAmount = 0;
                AccountAll.CreditAmount = Qty;
            }

            AccountAll.BalanceAmount = AllWarehousQty;
            this.db
                .Insertable<ProductAccountAll>(AccountAll)
                .ExecuteCommand();

            #endregion

            #region 总结余
            if(balanceAllInfo == null)
            {
                balanceAllInfo = new PABalanceAllEntity();
                balanceAllInfo.ShopVSN = ShopVSN;
                balanceAllInfo.ProductVSN = ProductVSN;
                balanceAllInfo.BalanceAmount = AllWarehousQty;
                balanceAllInfo.pDate = DateTime.Now;

                this.db
                    .Insertable<PABalanceAllEntity>(balanceAllInfo)
                    .ExecuteCommand();
            }
            else
            {
                balanceAllInfo.BalanceAmount = AllWarehousQty;
                this.db
                    .Updateable<PABalanceAllEntity>(balanceAllInfo)
                    .ExecuteCommand();
            }


            #endregion

            return 0;
        }

    }
}
